package com.ruoyi.lhky.service;

import com.ruoyi.lhky.mapper.ResearchUserMapper;
import com.ruoyi.lhky.mapper.UserMapper;
import com.ruoyi.lhky.pojo.ResearchUser;
import com.ruoyi.lhky.pojo.User;
import com.ruoyi.lhky.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private ResearchUserMapper researchUserMapper;

    public R register(User user) {
        user.setCreateTime(LocalDateTime.now());
        user.setStatus(0L);
        int result = userMapper.insert(user);
        if (result > 0) {
//            System.out.println(user);
            ResearchUser researchUser = new ResearchUser();
            researchUser.setUserId(user.getId());
            researchUser.setResearchId(1L);
            researchUserMapper.insert(researchUser);
            return new R(true, user);

        } else {
            return new R(false, "注册失败");
        }
    }

    public User findByAccount(String account) {
        return userMapper.selectByAccount(account);
    }

    public R login(User user) {
        User foundUser = userMapper.selectByAccount(user.getAccount());
        if (foundUser != null) {
            if (foundUser.getStatus() == 1) {
                return new R(true, foundUser);
            }
            if (foundUser.getPassword().equals(user.getPassword())) {
                foundUser = userMapper.getUserWithWorkplace(foundUser.getId());
                return new R(true, foundUser);
            } else {
                return new R(false, "账号或密码错误");
            }
        } else {
            return new R(false, "账号或密码错误");
        }
    }
    public User getUserById(Long id) {
        return userMapper.getUserWithWorkplace(id);
    }

    public R changePassword(String account, String currentPassword, String newPassword) {
        User user = userMapper.selectByAccount(account);
        if (user != null && user.getPassword().equals(currentPassword)) {
            user.setPassword(newPassword);
            int result = userMapper.updateById(user);
            if (result > 0) {
                return new R(true, "密码修改成功");
            } else {
                return new R(false, "密码修改失败");
            }
        } else {
            return new R(false, "当前密码错误");
        }
    }

}
